﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using QuanLyTiemVang.DTO;

namespace QuanLyTiemVang.DAO
{
    class TaiKhoanDAO
    {
        private static QUANLYTIEMVANGEntities dbContext = new QUANLYTIEMVANGEntities();

        public static TAIKHOAN SelectTaiKhoanByTenDangNhap(TAIKHOAN tk)
        {            
            var query = from d in dbContext.TAIKHOANs
                        where string.Equals(d.TenDangNhap, tk.TenDangNhap)==true
                        select d;
            if (query.Count()>0)
                return query.First();
            return null;
        }

        public static TAIKHOAN SelectTaiKhoanByEmail(TAIKHOAN tk)
        {                     
            var query = from d in dbContext.TAIKHOANs
                        where string.Equals(d.Email, tk.Email) == true
                        select d;
            if (query != null)
                return query.First();
            return null;
        }

        public static void Insert(TAIKHOAN tk)
        {
            var query = from d in dbContext.TAIKHOANs
                        where string.Equals(tk.TenDangNhap, d.TenDangNhap)
                        select d;
            if (query.Count()>0)
                throw new Exception("Tên đăng nhập đã tồn tại!");
            tk.MatKhau = BCrypt.Net.BCrypt.HashPassword(tk.MatKhau);
            dbContext.TAIKHOANs.Add(tk);
            dbContext.SaveChanges();
        }

        public static bool IsRightPassword(TAIKHOAN tk)
        {
            TAIKHOAN taiKhoan = SelectTaiKhoanByTenDangNhap(tk);
            if (taiKhoan == null)
                return false;
            return BCrypt.Net.BCrypt.Verify(tk.MatKhau, taiKhoan.MatKhau);                         
        }

        public static List<LOAITAIKHOAN> LoaiTaiKhoans()
        {
            return dbContext.LOAITAIKHOANs.ToList();
        }

        internal static bool KTraEmail(string email)
        {
            var query=(from d in dbContext.TAIKHOANs
                      where d.Email.Equals(email)
                      select d).ToList();
            if (query.Count > 0)
                return false;
            return true;
        }
    }
}
